/**
 * @chatset utf-8
 * atearsan/2013-10-25
 * 
 * background.js是与浏览器交互的js
 * 
 */
chrome.extension.onRequest.addListener(
	function(request, sender, sendResponse) {
		//console.log(sender.tab ? "from a content script:" + sender.tab.url : "from the extension");
		//console.log(request);
		//alert(request.action);//		console.log不会执行
		if(request.action == 'iconMsg') {
			if (request.blockCount > 0) {
	    		// 修改插件图标: 提示拦截了多少用户
				// 2015年 2月 2日 星期一 不更改icon, 因为更改icon会让icon变得有锯齿... 很郁闷
	    		//chrome.browserAction.setIcon({path: "img/green_48.png", tabId: sender.tab.id});
	    		chrome.browserAction.setBadgeText({text: request.blockCount + "", tabId: sender.tab.id});
				// 默认红色, 我怕强迫症患者一定要消掉那个红色点点. 现在深灰色
	    		chrome.browserAction.setBadgeBackgroundColor({color:[63,63,63,200], tabId: sender.tab.id});
	    		//sendResponse({farewell: "goodbye"});
	    	}
			else {
	    		//chrome.browserAction.setIcon({path: "img/green_48.png"});
				chrome.browserAction.setBadgeText({text: "", tabId: sender.tab.id});
	    		//sendResponse({}); // snub them.
	    	}
		}
	}
);

// 创建新tab (从sample中复制的 http://open.chrome.360.cn/extension_dev/cookies.html)
function focusOrCreateTab(url) {
  chrome.windows.getAll({"populate":true}, function(windows) {
    var existing_tab = null;
    for (var i in windows) {
      var tabs = windows[i].tabs;
      for (var j in tabs) {
        var tab = tabs[j];
        if (tab.url == url) {
          existing_tab = tab;
          break;
        }
      }
    }
    if (existing_tab) {
      chrome.tabs.update(existing_tab.id, {"selected":true});
    } else {
      chrome.tabs.create({"url":url, "selected":true});
    }
  });
}

// 点击icon的事件
chrome.browserAction.onClicked.addListener(function(tab) {
  var manager_url = chrome.extension.getURL("blacklist.html");
  focusOrCreateTab(manager_url);
});